package cn.yj.syslog.aspect.operatelog;

import cn.yj.syslog.common.DefaultRecords;
import cn.yj.syslog.common.OperateLog;
import cn.yj.common.UUIdUtils;
import cn.yj.commons.utils.HttpHeaderUtil;
import cn.yj.commons.utils.StringUtils;
import cn.yj.syslog.aspect.OncePleaseOne;
import cn.yj.syslog.entity.SysLog;
import cn.yj.syslog.filter.LogRequestWrapper;
import cn.yj.syslog.service.ISysLogService;
import com.alibaba.fastjson.JSONArray;
import org.aopalliance.intercept.MethodInvocation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.nio.charset.Charset;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.stream.Collectors;

/**
 * <br>
 *
 * @author 永健
 * @since 2020-12-17 17:34
 */
public class OperateLogMethodInterceptor extends OncePleaseOne {

    private static final Logger log = LoggerFactory.getLogger(OperateLogMethodInterceptor.class);

    private ISysLogService iSysLogService;

    public OperateLogMethodInterceptor(ISysLogService iSysLogService) {
        this.iSysLogService = iSysLogService;
    }


    @Override
    public Object doInvoke(MethodInvocation methodInvocation, HttpServletRequest request) throws Throwable {
        long now = System.currentTimeMillis();
        DefaultRecords defaultRecords = new DefaultRecords(request, iSysLogService);
        Object value = null;
        final ExecutorService executorService = Executors.newSingleThreadExecutor();
        defaultRecords.before(methodInvocation);
        try {
            value = methodInvocation.proceed();
        } catch (Throwable throwable) {

            executorService.execute(()->defaultRecords.error(throwable));
            throw throwable;
        } finally {
            Object finalValue = value;
            executorService.execute(() -> defaultRecords.after(finalValue));
            System.out.println();
            log.info("请求耗时：" + (System.currentTimeMillis() - now) + "/毫秒");
            executorService.shutdown();
        }
        return value;
    }


}
